﻿package com.xbniao.owms.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;



public class ServletUtils
{
	private ServletUtils()
	{
	}

	/**
	 * 根据key获取request中value值
	 * @param request
	 * @param sKey
	 * @return
	 */
	public static String getRequestValue(HttpServletRequest request, String sKey)
	{
		if (request.getParameter(sKey) != null)
		{
			return request.getParameter(sKey);
		}
		else
		{
			return "";
		}
	}

	/**
	 * 根据key获取request中values值
	 * @param request
	 * @param sKey
	 * @return
	 */
	public static String[] getRequestValues(HttpServletRequest request, String sKey)
	{
		if (request.getParameterValues(sKey) != null)
		{
			return request.getParameterValues(sKey);
		}
		else
		{
			return new String[0];
		}
	}

	/**
	 * 获取cookie值
	 */
	public static String getCookieValue(HttpServletRequest request, String sName)
	{
		Cookie[] cookies = request.getCookies();

		if (cookies != null)
		{
			for (Cookie cookie : cookies)
			{
				if (sName.equalsIgnoreCase(cookie.getName()))
				{
					return cookie.getValue();
				}
			}
		}

		return "";
	}

	/**
	 * 获取cookie值 
	 * @param request javax.servlet.http.HttpServletRequest
	 * @param response javax.servlet.http.HttpServletResponse
	 * @param sName Cookie
	 * @param sValue Cookie
	 * @param sDomain Cookie
	 * @param iTime Cookie
	 */
	public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String sName, String sValue, String sDomain, int iTime)
	{
		Cookie cookie = new Cookie(sName, sValue);

		cookie.setMaxAge(iTime);
		cookie.setPath("/");

		if (sDomain != null && !"".equals(sDomain))
		{
			cookie.setDomain(sDomain);
		}

		response.addCookie(cookie);
	}

	/**
	 * 获取客户端ip
	 * @param request
	 * @return
	 */
	public static String getRemoteAddr(HttpServletRequest request)
	{
		String sIP = request.getHeader("x-forwarded-for");

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
		{
			sIP = request.getHeader("Proxy-Client-IP");
		}

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
		{
			sIP = request.getHeader("WL-Proxy-Client-IP");
		}

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
		{
			sIP = request.getRemoteAddr();
		}

		if (!StringUtils.isEmpty(sIP))
		{
			int iIndexOf = sIP.indexOf(",");
			if (iIndexOf != -1)
			{
				sIP = sIP.substring(0, iIndexOf);
			}
		}

		return sIP == null ? "" : sIP;
	}
}